package com.yntsoft.realm;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import com.yntsoft.entity.ShiroUser;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
import java.util.Deque;
import java.util.LinkedList;

/**
 * <p>User: Zhang Kaitao
 * <p>Date: 14-2-18
 * <p>Version: 1.0
 */
public class KickoutSessionControlFilter extends AccessControlFilter {

    private String kickoutUrl; //踢出后到的地址
    private boolean kickoutAfter = false; //踢出之前登录的/之后登录的用户 默认踢出之前登录的用户
    private int maxSession = 1; //同一个帐号最大会话数 默认1

    private SessionManager sessionManager;
    private Cache<String, Deque<Serializable>> cache;

    public void setKickoutUrl(String kickoutUrl) {
        this.kickoutUrl = kickoutUrl;
    }

    public void setKickoutAfter(boolean kickoutAfter) {
        this.kickoutAfter = kickoutAfter;
    }

    public void setMaxSession(int maxSession) {
        this.maxSession = maxSession;
    }

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    public void setCacheManager(CacheManager cacheManager) {
        this.cache = cacheManager.getCache("shiro-kickout-session");
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    	
        Subject  subject = getSubject(request, response);
    	ShiroUser shiroUser = (ShiroUser) subject.getPrincipal();
    	//判断当前session的用户是否登陆  没有认证  并且没有  记住我
    	if(!subject.isAuthenticated() && !subject.isRemembered()){
    		//如果没有登陆直接进行之后的流程
    		return true;
    	}
    	Session session= subject.getSession();
    	String username = shiroUser.getUsercode();//获取当前登录用户帐号
    	Serializable  sessionId = session.getId();//获取当前session 的sessionId
    	Deque<Serializable> deque = cache.get(username);//获取保存在ehcache中的队列信息
    	if(deque == null){
    		deque = new LinkedList<Serializable>();
    		cache.put(username, deque);
    	}
    	//没有这个sessionId  并且没有被踢出
    	if(!deque.contains(session) && session.getAttribute("kickout") == null){
    		deque.push(sessionId);
    	}
    	while (deque.size() > maxSession) {
    		Serializable kickoutSessionId = null;
    		if(kickoutAfter){
    			kickoutSessionId = deque.removeFirst();
            } else {
    			kickoutSessionId = deque.removeLast();            	
            }
    		try {
				Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
				if(kickoutSession != null){
				     //设置会话的kickout属性表示踢出了
	                kickoutSession.setAttribute("kickout", true);
				}
			} catch (Exception e) {
			}
		}
    	if(session.getAttribute("lickout") != null){
    		//会话被踢出了
    		try {
				subject.logout();
			} catch (Exception e) {
			}
    		saveRequest(request);
    		WebUtils.issueRedirect(request, response, kickoutUrl);
    	}
        return true;
    }
}
